package com.project;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.sql.Timestamp;

@WebServlet("/getFlights")
public class GetFlightsServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 获取查询参数
        String fid = request.getParameter("fid");
        String starttime = request.getParameter("starttime");
        String endtime = request.getParameter("endtime");
        String takeoffstation = request.getParameter("takeoffstation");
        String arrivalstation = request.getParameter("arrivalstation");
        String boardingtime = request.getParameter("boardingtime");
        String position = request.getParameter("position");
        int page = Integer.parseInt(request.getParameter("page"));
        int pageSize = 20;

        // 构建查询条件
        List<String> flightConditions = new ArrayList<>();
        List<String> airlineConditions = new ArrayList<>();

        if (fid != null && !fid.isEmpty()) {
            flightConditions.add("fid=" + fid);
            airlineConditions.add("fid=" + fid);
        }
        if (starttime != null && !starttime.isEmpty()) {
            String formattedTime = starttime.replace('T', ' ') + ":00";
            flightConditions.add("starttime>=" + Timestamp.valueOf(formattedTime));
        }
        if (endtime != null && !endtime.isEmpty()) {
            String formattedTime = endtime.replace('T', ' ') + ":00";
            flightConditions.add("endtime<=" + Timestamp.valueOf(formattedTime));
        }
        if (takeoffstation != null && !takeoffstation.isEmpty()) {
            flightConditions.add("takeoffstation=" + takeoffstation);
        }
        if (arrivalstation != null && !arrivalstation.isEmpty()) {
            flightConditions.add("arrivalstation=" + arrivalstation);
        }
        if (boardingtime != null && !boardingtime.isEmpty()) {
            flightConditions.add("boardingtime=" + Timestamp.valueOf(boardingtime.replace('T', ' ')));
        }
        if (position != null && !position.isEmpty()) {
            airlineConditions.add("position=" + position);
        }
        airlineConditions.add("remain>0");
        flightConditions.add("1=1");

        // 查询航班数据
        DB_Flight dbFlight = new DB_Flight();
        DB_Airline dbAirline = new DB_Airline();

        List<String> airlineResults = dbAirline.find(airlineConditions);
        List<String> flightResults = dbFlight.find(flightConditions);

        // 合并数据并过滤
        List<String> combinedResults = new ArrayList<>();
        for (String airline : airlineResults) {
            String[] airlineData = airline.split(",");
            String airlineFid = airlineData[1];
            for (String flight : flightResults) {
                String[] flightData = flight.split(",");
                String flightFid = flightData[0];
                if (airlineFid.equals(flightFid)) {
                    combinedResults.add(airline + "," + flight);
                }
            }
        }

        // 计算总页数
        int totalPages = (int) Math.ceil((double) combinedResults.size() / pageSize);

        // 分页处理
        int startIndex = (page - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, combinedResults.size());
        List<String> paginatedResults = combinedResults.subList(startIndex, endIndex);

        // 构建 JSON 响应
        StringBuilder jsonResponse = new StringBuilder();
        jsonResponse.append("{");
        jsonResponse.append("\"flights\": [");
        for (int i = 0; i < paginatedResults.size(); i++) {
            String[] data = paginatedResults.get(i).split(",");
            jsonResponse.append("{");
            jsonResponse.append("\"fid\": \"").append(data[1]).append("\",");
            jsonResponse.append("\"date\": \"").append(data[2]).append("\",");
            jsonResponse.append("\"position\": \"").append(data[3]).append("\",");
            jsonResponse.append("\"remain\": \"").append(data[4]).append("\",");
            jsonResponse.append("\"starttime\": \"").append(data[6]).append("\",");
            jsonResponse.append("\"endtime\": \"").append(data[7]).append("\",");
            jsonResponse.append("\"takeoffstation\": \"").append(data[8]).append("\",");
            jsonResponse.append("\"arrivalstation\": \"").append(data[9]).append("\",");
            jsonResponse.append("\"boardingtime\": \"").append(data[10]).append("\"");
            jsonResponse.append("}");
            if (i < paginatedResults.size() - 1) {
                jsonResponse.append(",");
            }
        }
        jsonResponse.append("],");
        jsonResponse.append("\"currentPage\": ").append(page).append(",");
        jsonResponse.append("\"totalPages\": ").append(totalPages);
        jsonResponse.append("}");

        out.print(jsonResponse.toString());
        out.flush();
    }
}